package com.xiaotao.consumer;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.xiaotao.dto.OrderDto;
import com.xiaotao.mapper.OrderDetailMapper;
import com.xiaotao.mapper.OrdersMapper;
import com.xiaotao.service.WebSocketPushService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import static com.xiaotao.config.RabbitConfig.ORDER_CREATE_QUEUE;

@Component
@Slf4j
public class TopicConsumer {
    @Resource
    private OrdersMapper OrdersMapper;
    @Resource
    private OrderDetailMapper OrderDetailMapper;
    @Resource
    private WebSocketPushService wsPush;

    @RabbitListener(queues = ORDER_CREATE_QUEUE)

    public void receive(String msg, Channel channel, Message message){
        log.info("接收到消息：{}",msg);
        try {
//            Thread.sleep(20000);

            OrderDto Order = JSON.parseObject(msg, OrderDto.class);
            OrdersMapper.insert(Order.getOrders());
            OrderDetailMapper.insertBatch(Order.getOrderDetails());
//            OrderMapper.insertBatch(Order.getOrderDetailList());
//            if (Order != null){
//               OrderMapper.insert(Order);
//            }
            wsPush.sendOrderMsg(Order.getOrders().getUserId(), "订单已创建！订单号：" + Order.getOrders().getId());
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
           e.printStackTrace();
           try {
               channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
           } catch (Exception ex) {
               throw new RuntimeException(ex);
           }
        }
    }
}
